package middleware

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"shrimp-blog-server/app/dao"
	"shrimp-blog-server/utils"
	"strings"
)

func Ctx(r *ghttp.Request) {
	// 初始化，务必最开始执行
	customCtx := &dao.Context{
		Session: r.Session,
		Data:    make(g.Map),
	}
	dao.AppCtx.Init(r, customCtx)

	// 执行下一步请求逻辑
	r.Middleware.Next()
}

func Auth(req *ghttp.Request) {
	var isHasAccess = true
	// 获取session
	session := req.Session
	if session == nil {
		isHasAccess = false
	}
	if session.Get("user") == nil {
		isHasAccess = false
	}
	tokenString := req.Cookie.Get("Authorization")
	if tokenString == "" {
		isHasAccess = false
	}
	split := strings.Split(tokenString, " ")
	if len(split) != 2 {
		isHasAccess = false
	}
	if split[0] != "Bearer" {
		isHasAccess = false
	}
	token, err := utils.ParseToken(split[1])
	if err != nil {
		isHasAccess = false
	}
	if !token.Valid {
		isHasAccess = false
	}

	if !isHasAccess {
		if req.IsAjaxRequest() {

			utils.Response.JsonRedirectExit(req, 1, "", "/index")
		} else {
			req.Response.RedirectTo("/login")
		}
	} else {
		utils.RefreshToken(tokenString)
	}
}
